package com.cx.singleton;

/**
 * @author zhangshuai
 * @version V1.0
 * @Project Java2_26
 * @Package com.cx.singleton
 * @Description:
 * @Date 2025/5/27 8:12
 */

public class LazySingleton {

    //懒汉式：是延迟加载，我们用的时候才去创建，创建单例对象

    //定义静态变量，存储单例对象
    private static LazySingleton instance;

    //构造函数私有，防止外部创建实例
    private LazySingleton() {
        System.out.println("懒加载创建实例对象");
    }

    //提供静态方法，返回单例对象,线程不安全，多线程环境下可能会创建多个实例
    public static  LazySingleton getInstance() {
        //同步代码块的效率要比同步方法效率高
        synchronized(LazySingleton.class){
            if (instance == null) {
                instance = new LazySingleton();
            }
            return instance;
        }


    }

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            new Thread(()->{
                LazySingleton instance1 = LazySingleton.getInstance();
                System.out.println(instance1);
            }).start();
            new Thread(()->{
                LazySingleton instance1 = LazySingleton.getInstance();
                System.out.println(instance1);
            }).start();
            new Thread(()->{
                LazySingleton instance1 = LazySingleton.getInstance();
                System.out.println(instance1);
            }).start();
        }

        new Thread(()->{
            LazySingleton instance1 = LazySingleton.getInstance();
            System.out.println(instance1);
        }).start();
        new Thread(()->{
            LazySingleton instance1 = LazySingleton.getInstance();
            System.out.println(instance1);
        }).start();
        new Thread(()->{
            LazySingleton instance1 = LazySingleton.getInstance();
            System.out.println(instance1);
        }).start();
    }

}